import matplotlib.pyplot as plt
import re
import abstract_decoder


class CoordsDecoder(abstract_decoder.AbstractDecoder):
    def __init__(self):
        super().__init__("coords")

    def decode(self, data, key):
        coords = []
        matches = re.findall(r"\d+\s*[,-_@#$%^&*;:+]\s*\d+", data)
        for item in matches:
            coord = decoder._parse_coord(item)
            coords.append(coord)

        x, y = zip(*coords)
        plt.scatter(x, y)
        plt.gca().invert_yaxis()  # 如果需要反转y轴
        plt.show()
        return "使用坐标解析器解密坐标数据"

    def is_valid(self, data, key):
        patten = r"^([([{]\s*\d+\s*[,-_@#$%^&*;:+]\s*\d+\s*[)\]}]\s*)*$"        
        return bool(re.fullmatch(patten, data))

    def _parse_coord(self, item: str) -> tuple[int, int]:
        matches = re.findall(r"\d+", item)
        return int(matches[0]), int(matches[1])
    

if __name__ == "__main__":
    decoder = CoordsDecoder()
    file_path = "test-data/coords.txt"
    with open(file_path, "r") as f:
        data = f.read()
        key = "123456"
        if decoder.is_valid(data, key):
            print(decoder.decode(data, key))
        else:
            print("数据不符合坐标格式")